import 'package:dio/dio.dart';
import 'package:flutter/material.dart';
import 'package:flutter_app/global/global_api.dart';
import 'package:flutter_app/icon/constant_icons.dart';
import 'package:flutter_app/main/content/content.dart';
import 'package:flutter_app/main/content/model/content_model.dart';
import 'package:flutter_app/main/main/model/home_banner_entity.dart';
import 'package:flutter_app/main/main/model/home_list_entity.dart';
import 'package:flutter_swiper/flutter_swiper.dart';
import 'package:pull_to_refresh/pull_to_refresh.dart';

class HomeTableWidget extends StatefulWidget {
  const HomeTableWidget({super.key});

  @override
  HomeTablePage createState() => HomeTablePage();
}

class HomeTablePage extends State<HomeTableWidget> {
  List<HomeBannerData> bannerData = [];
  List<HomeListDataDatas> listData = [];
  RefreshController controller = RefreshController(initialRefresh: false);
  int pageIndex = 0;
  bool isRefresh = true;

  Future<void> getBannerData() async {
    String url = GlobalApi.homeBannerUrl;
    Response response = await Dio().get(url);
    var data = response.data;
    HomeBannerEntity bannerEntity = HomeBannerEntity.fromJson(response.data);
    setState(() {
      bannerData.clear();
      bannerData.addAll(bannerEntity.data);
    });
  }

  void onRefresh() async {
    isRefresh = true;
    pageIndex = 0;
    getListData();
  }

  void onLoading() async {
    isRefresh = false;
    pageIndex++;
    getListData();
  }

  Future<void> getListData() async {
    String url = GlobalApi.homeListUrl(pageIndex);
    Response response = await Dio().get(url);
    var data = response.data;
    HomeListEntity listEntity = HomeListEntity.fromJson(data);
    setState(() {
      if (isRefresh) {
        listData.clear();
        listData.addAll(listEntity.data.datas);
        controller.refreshCompleted();
      } else {
        listData.addAll(listEntity.data.datas);
        controller.loadComplete();
      }
    });
  }

  @override
  void initState() {
    super.initState();
    getBannerData();
    onRefresh();
  }

  @override
  Widget build(BuildContext context) {
    return SizedBox(
      height: double.infinity,
      width: double.infinity,
      child: SmartRefresher(
        controller: controller,
        enablePullDown: true,
        enablePullUp: true,
        header: const MaterialClassicHeader(),
        onRefresh: onRefresh,
        onLoading: onLoading,
        child: ListView.builder(
          itemBuilder: (c, i) {
            if (i == 0) {
              return Container(
                width: double.infinity,
                height: 200,
                alignment: Alignment.center,
                child: Swiper(
                    key: ValueKey(bannerData.length),
                    itemBuilder: (BuildContext context, int index) {
                      return Image.network(
                        bannerData[index].imagePath,
                        fit: BoxFit.fill,
                      );
                    },
                    itemCount: bannerData.length,
                    autoplay: true,
                    pagination: const SwiperPagination(builder: DotSwiperPaginationBuilder(
                      size: 0,
                      activeSize: 0
                    )),
                    scale: 0.7,
                    layout: SwiperLayout.DEFAULT,
                    onTap: (index) => {
                          Navigator.pushNamed(c, ContentWidget.RouteName,
                              arguments: ContentModel(bannerData[index].url))
                        }),
              );
            } else {
              return ListTile(
                onTap: () {
                  Navigator.pushNamed(c, ContentWidget.RouteName,
                      arguments: ContentModel(listData[i - 1].link));
                },
                enabled: true,
                title: Column(
                  crossAxisAlignment: CrossAxisAlignment.start,
                  children: [
                    Container(
                      margin: const EdgeInsets.fromLTRB(0, 10, 0, 0),
                      child: Text(
                        listData[i - 1].shareUser,
                        style: const TextStyle(
                            color: Colors.black54, fontSize: 12),
                      ),
                    ),
                    Container(
                      margin: const EdgeInsets.fromLTRB(0, 5, 0, 0),
                      child: Text(listData[i - 1].title,
                          style: const TextStyle(
                              color: Colors.black87, fontSize: 14)),
                    ),
                    Container(
                      margin: const EdgeInsets.fromLTRB(0, 5, 0, 0),
                      padding: const EdgeInsets.only(bottom: 10),
                      child: Text(
                          '${listData[i - 1].chapterName}/${listData[i - 1].superChapterName}',
                          style: const TextStyle(
                              color: Colors.black54, fontSize: 12)),
                    ),
                  ],
                ),
                trailing: Column(
                  crossAxisAlignment: CrossAxisAlignment.end,
                  children: [
                    Text(
                      listData[i - 1].niceDate,
                      style: const TextStyle(fontSize: 12, color: Colors.black54),
                    ),
                    const SizedBox(
                      height: 21,
                      width: 10,
                    ),
                    const Icon(
                      CustantIcons.squareCollectNoSelect,
                      size: 20,
                    ),
                  ],
                ),
              );
            }
          },
          itemCount: listData.length,
        ),
      ),
    );
  }
}
